package com.wjm.serversocket.test2;

import com.wjm.serversocket.test1.UploadPicServer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * //本地文件复制 测试
 *
 * //本地文件复制 测试 支持断点，具体断点实现方法看注释
 */
public class RandomAccessFileTest {

    public static void main(String[] args) throws Exception {

//        oneThread2();//本地文件复制 测试

        oneThread3();//本地文件复制 测试 支持断点

//        oneThread();
    }

    private static void oneThread3() throws Exception {
        //输入流
        File file = new File(UploadPicServer.fileStr);
        long length = file.length();
        FileInputStream fis = new FileInputStream(UploadPicServer.fileStr);

        //输出流
        File fileDir = new File(UploadPicServer.pcPf + File.separator + UploadPicServer.serverfilePath);//i:\\server
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File fileOut = new File(fileDir, UploadPicServer.fileName);

        byte[] buf = new byte[20480];
        int len;
        float lenCount = 0;//用于计算上传进度
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(0); // 设置精确到小数点后2位
        String lastResult = null;
        if (fileOut.exists()) {  //文件存在，断点

            // 存储在服务器中的文件长度
            long fileSize = fileOut.length();//111111111111111111111111111
            System.out.println("断点，文件已复制大小==》"+fileSize);
            long pointSize = 0;
            // 判断是否已下载完成
            if (length > fileSize) {
                // 断点下载
                pointSize = fileSize;
            } else {
                // 重新下载
                fileOut.delete();
                fileOut.createNewFile();
            }

            RandomAccessFile rafOut = new RandomAccessFile(fileOut, "rw");//222222222222222222222
            rafOut.seek(pointSize);//指定从这开始断点读

            RandomAccessFile raffIs = new RandomAccessFile(UploadPicServer.fileStr, "rw");//222222222222222222222222222
            raffIs.seek(pointSize);//指定从这开始断点写

            lenCount=fileSize;//文件从这开始计进度//333333333333333333333333333

            while ((len = raffIs.read(buf)) != -1) {
                lenCount += len;
                float bfbD = lenCount / length * 100;
                String result = numberFormat.format(bfbD);
                if (!result.equals(lastResult)) {
//                    if ("0".equals(result) || "10".equals(result) || "50".equals(result) || "90".equals(result) || "100".equals(result))
                        System.out.println(Thread.currentThread().getName() + "断点复制进度：" + result + "%");//
                }
                lastResult = result;


                rafOut.write(buf, 0, len);//44444444444444444444444444444
                Thread.sleep(1);
            }
            rafOut.close();
        } else {//文件不存在，正常读写复制
            FileOutputStream fos = new FileOutputStream(fileOut);

            while ((len = fis.read(buf)) != -1) {
                lenCount += len;
                float bfbD = lenCount / length * 100;
                String result = numberFormat.format(bfbD);
                if (!result.equals(lastResult)) {
                    if ("0".equals(result) || "10".equals(result) || "50".equals(result) || "90".equals(result) || "100".equals(result))
                        System.out.println(Thread.currentThread().getName() + "新文件复制进度：" + result + "%");//
                }
                lastResult = result;

                fos.write(buf, 0, len);
                Thread.sleep(1);
            }
            fos.close();
        }
        fis.close();

    }

    private static void oneThread2() throws Exception {

        //输入流
        FileInputStream fis = new FileInputStream(UploadPicServer.fileStr);

        //输出流
        File fileDir = new File(UploadPicServer.pcPf + File.separator + UploadPicServer.serverfilePath);//i:\\server
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(new File(fileDir, new SimpleDateFormat("yyyyMMddHHmmssSSS_").format(new Date()).toString() + UUID.randomUUID() + UploadPicServer.fileName));

        byte[] buf = new byte[1024];
        int len;
        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fis.close();
        fos.close();

    }

    private static void oneThread() throws Exception {
      /*
        FileInputStream fis=new FileInputStream("");
        File filefff=new File("");
        long fileLength = filefff.length();

        File directory = new File(panFu + pathChar + "receive"+ pathChar +"" + ip + pathChar);
        if (!directory.exists()) {
            directory.mkdirs();
        }


        int length = 0;

        byte[] bytes = new byte[1024];
        File file = new File(directory.getAbsolutePath() + pathChar + fileName);
        if (!file.exists()) {
            // 不存在
            fos = new FileOutputStream(file);
            // 开始接收文件
            while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
                fos.write(bytes, 0, length);
                fos.flush();
            }
        } else {
            // 存储在服务器中的文件长度
            long fileSize = file.length(), pointSize = 0;
            // 判断是否已下载完成
            if (fileLength > fileSize) {
                // 断点下载
                pointSize = fileSize;
            } else {
                // 重新下载
                file.delete();
                file.createNewFile();
            }

            rantmpfile = new RandomAccessFile(file, "rw");
            *//*
         * java.io.InputStream.skip() 用法：跳过 n 个字节（丢弃） 如果 n
         * 为负，则不跳过任何字节。
         *//*
            // dis.skip(pointSize); （已从客户端读取进度）
            *//**
         * 资源，文件定位（游标、指针） 将ras的指针设置到8，则读写ras是从第9个字节读写到
         *//*
            rantmpfile.seek(pointSize);

            while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
                rantmpfile.write(bytes, 0, length);
            }
        }*/
    }
}
